//
//  ViewController.m
//  mark
//
//  Created by student5 on 2021/12/9.
//

#import "ViewController.h"
//#import "TableViewCell.h"
#import "SettingViewController.h"
#import "CreateRecordViewController.h"
#import "detailView.h"
//#import "settingView.h"

@interface ViewController ()
//@property(strong,nonatomic)UIBarButtonItem *add_button;//点击这个按钮会弹出添加新记录  //好像没有必要加
@property(strong,nonatomic)UIBarButtonItem *set_item;//左边的设置按钮，但是加了好像也没有必要
@property(strong,nonatomic)UITableView *record;//
@property NSInteger chose;
//@property(strong,nonatomic)settingView *leftview;
@property(strong,nonatomic)UIView *backgroundView;//半透明背景
@property(strong,nonatomic)UIWindow *window;//半透明背景
@property(strong,nonatomic)NSMutableArray *time_path_array;   //存储提醒时间路径
//@property(strong,nonatomic)NSDate *time_array;                //存储所有记录的时间
@property(strong,nonatomic)NSMutableArray *summary_path_array;//存储简介的路径
@property(strong,nonatomic)NSMutableArray *url_path_array;    //存储url的路径
@property(strong,nonatomic)NSMutableArray *html_path_array;   //html文件路径
@property(strong,nonatomic)NSMutableArray *font_path_array;   //字体大小路径
@property (strong,nonatomic) NSString *paths;                 //document的路径
@property(strong,nonatomic) NSString *record_count_string;    //这个文件里的数存的是下面那个int count
@property(nonatomic) int count;  //这个是record的数量，不是record用到的编号
//@property(strong,nonatomic)detailView *detailView;//点击对应记录后跳转的页面

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationItem setTitle:@"记录生活"];
    [self initData];
    //[self setbtn];
    [self addbtn];
    //[self InitializeLeftView];
    [self initTableView];
}



-(void)initData{//初始化缓存目录以及存储用数组
    NSLog(@"init");
    //消掉 icon 上 红色数字
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    //获取docunment的路径
    self.paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    //初始化记录条数
    NSError *error;
    //存储record使用到的编号的路径
    self.record_count_string = [NSString stringWithFormat:@"record_count.txt"];
    self.record_count_string = [self.paths stringByAppendingPathComponent:self.record_count_string];
    self.time_path_array = [[NSMutableArray alloc]init];
    self.summary_path_array = [[NSMutableArray alloc]init];
    self.url_path_array = [[NSMutableArray alloc]init];
    self.html_path_array = [[NSMutableArray alloc]init];
    self.font_path_array = [[NSMutableArray alloc]init];  //[4]字体大小
    if(![[NSFileManager defaultManager]fileExistsAtPath:self.record_count_string]){
        //使用一个文件来存record使用到的编号的路径，如果没有的话说明app首次使用，需要创建txt
        NSLog(@"not exist");
        [@"0" writeToFile:self.record_count_string atomically:YES encoding:NSUTF8StringEncoding error:&error];//初始化为0
        self.count = 0;
    }
    else{
        NSString *count_string;
        count_string = [NSString stringWithContentsOfFile:self.record_count_string encoding:NSUTF8StringEncoding error:&error];
        self.count = [count_string intValue]; //record的数量
    }
    int i = 0;
    NSString *url_help_search_string;//辅助搜索用字符串
    NSString *summary_help_search_string;
    NSString *date_help_search_string;
    NSString *html_help_search_string;
    NSString *font_help_search_string;
    
    int j = 0;
    while(i < self.count){//遍历所有这些用过的编号
        NSLog(@"i %d;j %d;self.count %d",i,j,self.count);
        
        summary_help_search_string = [NSString stringWithFormat:@"summary%d.txt",j];
        date_help_search_string = [NSString stringWithFormat:@"date%d.txt",j];
        url_help_search_string = [NSString stringWithFormat:@"url%d.txt",j];
        html_help_search_string = [NSString stringWithFormat:@"html%d",j];
        font_help_search_string = [NSString stringWithFormat:@"font%d.txt",j];
        
        url_help_search_string = [self.paths stringByAppendingPathComponent:url_help_search_string];
        summary_help_search_string = [self.paths stringByAppendingPathComponent:summary_help_search_string];
        date_help_search_string = [self.paths stringByAppendingPathComponent:date_help_search_string];
        html_help_search_string = [self.paths stringByAppendingPathComponent:html_help_search_string];
        font_help_search_string = [self.paths stringByAppendingPathComponent:font_help_search_string];
        
        if([[NSFileManager defaultManager]fileExistsAtPath:date_help_search_string]){
            //判断这个路径是否存在，就是判断这个文件名是否对应了一个记录
            [self.time_path_array addObject:date_help_search_string];
            [self.summary_path_array addObject:summary_help_search_string];
            [self.url_path_array addObject:url_help_search_string];
            [self.html_path_array addObject:html_help_search_string];
            [self.font_path_array addObject:font_help_search_string];
            //如果是的话就把这个记录对应的路径加到相应的数组里面去
            i++;
            //并且再把i++表明已经找到了一个记录
        }
        j++;
        //接着往上找
    }
    [self sort_time];//给记录按时间排序
}


/*- (void)setbtn{//设置按钮
    UIButton *set_button=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 20)];

    //[leftbutton setBackgroundColor:[UIColor blackColor]];

    [set_button setTitle:@"设置" forState:UIControlStateNormal];
    [set_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //leftbutton.imageView.image = ;   导入按钮图标
    [set_button addTarget:self action:@selector(rightviewpressed:) forControlEvents:UIControlEventTouchUpInside];//添加事件
    self.set_item=[[UIBarButtonItem alloc]initWithCustomView:set_button];
    
  
    self.navigationItem.leftBarButtonItem = self.set_item;
}*/





- (void)addbtn{  //导航栏右侧的按钮，添加记录用
    UIBarButtonItem *add_button = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addButtonPressed:) ];
    NSArray *buttonItem = @[add_button];
    self.navigationItem.rightBarButtonItems = buttonItem;
    //not finished
}






/*-(void)InitializeLeftView{
    //初始化了leftview
    _leftview = [[settingView alloc]init];
    //位置
    _leftview.view.frame = CGRectMake(0, 0, self.view.frame.size.width *3/4, self.view.frame.size.height);
    _leftview.view.tag = 11;//
}*/




-(void)addButtonPressed:(id)sender{//添加新的记录的函数
    NSLog(@"addButtonPressed");
    CreateRecordViewController* cv = [[CreateRecordViewController alloc] init];
    cv.modalPresentationStyle = 0;//防止页面下移
    cv.father_view = self;//用于页面间通讯
    [self presentViewController:cv animated:YES completion:nil];
}


/*
- (void)rightviewpressed:(UIButton *)sender{//左边栏弹回
    NSLog(@"leftview go back");
    //NSLog([[NSString alloc]initWithFormat:@"%d",self.chose]);
    if (_chose == 0) {
        [self show];
    }
}*/
 


//弹出左边的设置栏
/*-(void)show{
    NSLog(@"show");
    //1. 取出window
    self.window = [[UIApplication sharedApplication] keyWindow];
    //2. 创建背景视图
    self.backgroundView = [[UIView alloc]init];
    self.backgroundView.frame = self.window.bounds;
    //3. 背景颜色,0.4不透明度
    self.backgroundView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.3];
    [self.window addSubview:self.backgroundView];
    //4. 把需要展示的控件添加上去
    [self.window addSubview:self.leftview.view];
    //5.动画
    NSLog(@"leftview_animate");
    self.backgroundView.alpha = 0;//初始透明为0
    self.leftview.view.transform =  CGAffineTransformMakeTranslation(-(self.leftview.view.bounds.size.width), 0.01);
    [UIView animateWithDuration:0.5 animations:^{
        self.leftview.view.transform = CGAffineTransformMakeTranslation(0.01, 0.01);//动画
        self.backgroundView.alpha = 1;//动画结束后透明度为1
    }];
    //6.给背景添加一个手势，移除视图
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(close:)];
    [self.backgroundView addGestureRecognizer:tap];
}*/



//收回设置栏
/*
-(void)close:(id)sender{
    NSLog(@"close");
    //加入动画

    //remove 边栏和背景
    [UIView animateWithDuration:0.5 animations:^{
        self.leftview.view.transform = CGAffineTransformMakeTranslation(-(self.leftview.view.bounds.size.width), 0.01);
        self.backgroundView.alpha = 0;//动画结束后透明度为0
    }completion:^(BOOL finished){
        [self.leftview.view removeFromSuperview];
        [self.backgroundView removeFromSuperview];
    }];

    
    
    //弹出状态设回0
    _chose = 0;
}*/



-(void)initTableView{
    if(self.record == nil){
        self.record = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height-100) style:UITableViewStyleGrouped];
        self.record.dataSource = self;
        self.record.delegate = self;
        self.record.backgroundColor = [UIColor clearColor];
       [self.record setScrollEnabled:YES]; //可以滑动
        self.record.separatorStyle = UITableViewCellSeparatorStyleNone;//去除分割线
    }
    [self.view addSubview:self.record];
    //return self.record;
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // 返回值是多少现在有几个分区，这个值应该等于self.count
    return self.time_path_array.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 2;
}




//使用代理方法绘制cell的边框
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(tintColor)]) {
        CGFloat cornerRadius = 10.f;
        CAShapeLayer *layer = [[CAShapeLayer alloc] init];
        CGMutablePathRef pathRef = CGPathCreateMutable();
        CGRect bounds = CGRectInset(cell.bounds, 10, 0);
        BOOL addLine = NO;
        if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
            CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
        } else if (indexPath.row == 0) {
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
            
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
            
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
            //在底下再加一条线
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
            
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
            addLine = YES;
        } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
            
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
            
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
            
        } else {
            CGPathAddRect(pathRef, nil, bounds);
            addLine = YES;
        }
        
        layer.path = pathRef;
        CFRelease(pathRef);
        //颜色修改
        layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.0f].CGColor;
        layer.strokeColor=[UIColor blackColor].CGColor;
        if (addLine == YES) {
            CALayer *lineLayer = [[CALayer alloc] init];
            CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
            lineLayer.frame = CGRectMake(CGRectGetMinX(bounds)+10, bounds.size.height-lineHeight, bounds.size.width-10, lineHeight);
            [layer addSublayer:lineLayer];
        }
        UIView *testView = [[UIView alloc] initWithFrame:bounds];
        [testView.layer insertSublayer:layer atIndex:0];
        cell.backgroundView = testView;
    }
    //加入动画
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 设置一个标示符
    static NSString *cell_id = @"cell_id";
    NSError *error;
    //
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
    // 判断cell是否存在
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_id];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//防止按钮被按过后变灰
    }
    // 分别给每个分区的单元格设置显示的内容
    if(indexPath.row == 0){
        NSString *time_str = [NSString stringWithContentsOfFile:self.time_path_array[indexPath.section] encoding:NSUTF8StringEncoding error:&error];
        NSString *show_str1 = [NSString stringWithFormat:@"提醒时间  %@",time_str];
        cell.textLabel.text  = show_str1;
    }else if (indexPath.row == 1){
        NSString *summary_str = [NSString stringWithContentsOfFile:self.summary_path_array[indexPath.section] encoding:NSUTF8StringEncoding error:&error];
        NSString *show_str2 = [NSString stringWithFormat:@"简介  %@",summary_str];
        cell.textLabel.text = show_str2;
    }
    return cell;
}




-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{//点击后跳转对应的子页面
    NSLog(@"detail view btn pressed");
    detailView* de = [[detailView alloc] init];
    NSMutableArray *send_data_path = [[NSMutableArray alloc] init];
    
    NSLog(@"%ld",indexPath.section);
    
    [send_data_path addObject:self.summary_path_array[indexPath.section]];
    [send_data_path addObject:self.time_path_array[indexPath.section]];
    [send_data_path addObject:self.url_path_array[indexPath.section]];
    [send_data_path addObject:self.html_path_array[indexPath.section]];
    [send_data_path addObject:self.font_path_array[indexPath.section]];
    //1
    
    de.data_path = send_data_path;
    de.father_view = self;
    de.modalPresentationStyle = 0;//解决在IOS13开发中跳转页面下移的问题
    [self presentViewController:de animated:YES completion:nil];
}


-(void)addData:(NSMutableArray *)t_path{
    NSLog(@"add obj");
    NSMutableArray *array = t_path;
    NSError *error;
    [self.summary_path_array addObject: array[0]];
    [self.time_path_array addObject: array[1]];
    [self.url_path_array addObject:array[2]];
    [self.html_path_array addObject:array[3]];  //html文件
    [self.font_path_array addObject:array[4]];  //字体大小
    if(![[NSFileManager defaultManager]fileExistsAtPath:self.record_count_string]){
        //判断这个路径是不是存在，虽然说没有必要
        NSLog(@"not exist");
    }
    self.count++;
    NSString *int_string = [NSString stringWithFormat:@"%d",self.count];
    [int_string writeToFile:self.record_count_string atomically:YES encoding:NSUTF8StringEncoding error:&error];//writeFile 为覆盖写法
    [self.record reloadData]; //tableview自带的方法，重新加载tableview
}


-(void)deleteData:(NSMutableArray *)t_path{

        if(![[NSFileManager defaultManager] fileExistsAtPath:t_path[0]]){
            NSLog(@"deleteData_summary: ERROR");
        }
        [[NSFileManager defaultManager] removeItemAtPath:t_path[0] error:nil];//删除缓存中的文件
        [self.summary_path_array removeObject:t_path[0]];//从数据队列中删除
        if(![[NSFileManager defaultManager] fileExistsAtPath:t_path[1]]){
            NSLog(@"deleteData_time: ERROR");
        }
        [[NSFileManager defaultManager] removeItemAtPath:t_path[1] error:nil];//删除缓存中的文件
        [self.time_path_array removeObject:t_path[1]];//从数据队列中删除
        
        [[NSFileManager defaultManager]removeItemAtPath:t_path[2] error:nil];
        [self.url_path_array removeObject:t_path[2]];
    
        [[NSFileManager defaultManager]removeItemAtPath:t_path[3] error:nil];
        [self.html_path_array removeObject:t_path[3]];
    
        [[NSFileManager defaultManager]removeItemAtPath:t_path[4] error:nil];
        [self.font_path_array removeObject:t_path[4]];
        self.count--;
    
        NSString *int_string = [NSString stringWithFormat:@"%d",self.count];
        [int_string writeToFile:self.record_count_string atomically:YES encoding:NSUTF8StringEncoding error:nil];//writeFile 为覆盖写法
    [self.record reloadData]; //tableview自带的方法
}




-(void)reloadTableViewData{
    NSLog(@"reload");
    [self.record reloadData]; //tableview自带的方法
}




-(void)sort_time{
    //冒泡排序
    NSError *error;
    for(int i = 0;i < self.count - 1;i++){
        for(int j = self.count - i - 1;j > 0;j--){
            NSString *time_str0 = [NSString stringWithContentsOfFile:self.time_path_array[j] encoding:NSUTF8StringEncoding error:&error];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm a"];  //格式设置
            NSDate *time0 = [dateFormatter dateFromString:time_str0];  //格式转换
            
            NSString *time_str1 = [NSString stringWithContentsOfFile:self.time_path_array[j-1] encoding:NSUTF8StringEncoding error:&error];
            NSDate *time1 = [dateFormatter dateFromString:time_str1];  //格式转换
            
            if([self compare_time:time0 compare_time:time1]){
                NSString *mid;
                mid = self.time_path_array[i];
                self.time_path_array[i] = self.time_path_array[j];
                self.time_path_array[j] = mid;
                
                mid = self.summary_path_array[i];
                self.summary_path_array[i] = self.summary_path_array[j];
                self.summary_path_array[j] = mid;
                
                mid = self.url_path_array[i];
                self.url_path_array[i] = self.url_path_array[j];
                self.url_path_array[j] = mid;
            }
        }
    }
}




-(BOOL)compare_time:(NSDate *)time_0 compare_time:(NSDate *)time_1{  //j
    
    if([time_0 compare:time_1] == -1){  //time0比较小
        return true;
    }
    else{
        return false;
    }
}
@end
